

import dayjs from "dayjs";
import { useState } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import { PageContainer, ScrollView, Text, View } from "@tarojs/components";

import ByRow from "@/components/ui/ByRow";
import Moment from "@/components/app/Moment";
import Card from "@/components/common/Card";
import ByIcon from "@/components/ui/ByIcon";
import ByText from "@/components/ui/ByText";
import Page from "@/components/common/Page";
import FooterNav from "./components/FooterNav";
import BySquare from "@/components/ui/BySquare";
import ListView from "@/components/app/ListView";
import PopupContainer from "@/components/app/PopupContainer";

import ApiCrm from "@/api/crm";
import ApiMokan from "@/api/mokan";
import useFetch from "@/hooks/useFetch";
import { convertSeconds } from "@/utils";

const Record = ({ source, onClick }) => {
  const {
    workerName,
    workerType,
    workerHours,
    workerStartDate,
    workerEndDate,
  } = source;

  const dutation =
    workerEndDate && workerStartDate
      ? dayjs(workerEndDate).diff(workerStartDate, "day") + 1
      : 0;

  const { hour, min } = convertSeconds(workerHours, ["hour", "min"]);
  return (
    <Card className="mx-3 my-2">
      <ByRow content="between" align="center">
        <ByText bold className="text-lg">
          {workerName}
        </ByText>
        {workerHours > 0 ? (
          <View className="text-third text-sm">
            <Text>
              打卡<Text className="text-base">{dutation}</Text>天
            </Text>

            <Text className="mx-1">
              共
              {hour > 0 && (
                <>
                  <Text className="text-base">{hour}</Text>
                  <Text>小时</Text>
                </>
              )}
              {min > 0 && (
                <>
                  <Text className="text-base">{min}</Text>
                  <Text>分钟</Text>
                </>
              )}
            </Text>

            <ByIcon name="Clock" onClick={onClick} />
          </View>
        ) : (
          <Text className="text-sm text-third">无打卡记录</Text>
        )}
      </ByRow>

      <ByRow className="text-xs text-third mt-2" content="between">
        <Text>{workerType}</Text>
        {workerStartDate && (
          <Text>
            <Moment value={workerStartDate} />
            <Text className="px-1">~</Text>
            <Moment value={workerEndDate} />
          </Text>
        )}
      </ByRow>
    </Card>
  );
};

const signTypeMap = {
  0: "签到",
  1: "签退",
};

export default () => {

  const { params } = useRouter()
  const intentCustomerId = Number(params.intentCustomerId)

  const { loading, data } = useFetch<{
    workerAttendanceRecordList: any[];
  }>(ApiCrm.getWorkerAttendanceRecord, {
    defaultParams: [{ intentCustomerId }],
  });

  const list = data?.workerAttendanceRecordList || [];
  const [records, setRecords] = useState<any>();


  const { data: customerData } = useFetch<any>(ApiCrm.customerDetail, {
    defaultParams: [{ intentCustomerId }],
  });

  // 解绑设备
  const { loading: unbindLoading, run: runUnbind } = useFetch(
    ApiMokan.unBindDevice,
    {
      manual: true,
      showErrorToast: true,
      onSuccess() {
        Taro.showToast({ title: "解绑成功" });
        setTimeout(() => {
          Taro.reLaunch({
            url:
              `/packageProject/pages/detail/index?intentCustomerId=` +
              intentCustomerId,
          });
        }, 1500);
      },
    }
  );


  const toUnbind = async () => {
    if (unbindLoading) return;

    const { confirm } = await Taro.showModal({
      title: "解除摄像头绑定",
      content: "解绑后，需要重新绑定方可使用；其他工地可绑定本摄像头",
    });

    if (confirm) runUnbind({ intentCustomerId, projectId });
  };

  const projectId = customerData?.intentCustomer.mkId;
  return (
    <>
      <Page
        footerSticky
        slotFooter={
          <FooterNav active={1} intentCustomerId={intentCustomerId} />
        }
      >
        <ListView loading={loading} isEmpty={list.length == 0}>
          {list?.map((item) => (
            <Record
              key={item.id}
              source={item}
              onClick={() => setRecords(item)}
            />
          ))}
        </ListView>
      </Page>

      <PageContainer show={records} onAfterLeave={() => setRecords(undefined)}>
        <PopupContainer
          title={`${records?.workerName}的打卡明细`}
          onCancel={() => setRecords(undefined)}
        >
          <ScrollView className="px-4 h-[50vh]" scroll-y >
            {records?.list?.map((item) => (
              <View className="py-2 border-b-1 border-[#ddd]" key={item.signTime}>
                <ByText className="pr-5">{signTypeMap[item.signType]}</ByText>
                <ByText type="second">{item.signTime}</ByText>
              </View>
            ))}
          </ScrollView>
        </PopupContainer>
      </PageContainer>

      {projectId && (
        <BySquare
          className="bg-error fixed bottom-[200px] right-2 z-10"
          size={80}
          onClick={toUnbind}
        >
          <ByIcon name="Unbind" color="#fff" />
        </BySquare>
      )}

    </>

  );
};
